import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { LayerManageService } from '../../core/services/layer-manage.service';
import { MenuService } from '../../core/services/menu.service';
import { LayerMessageService } from '../../core/services/layer-message.service';
import { MapService } from '../../core';
import { OverviewService } from './overview.service';
import { NzModalService } from 'ng-zorro-antd/modal';
import { MapFeatureInfoComponent } from 'src/app/shared/components/map-feature-info/map-feature-info.component';
import { RainfallTrendComponent } from './components/rainfall-trend/rainfall-trend.component';
import dayjs from 'dayjs';
import { WaterLevelComponent } from './components/water-level/water-level.component';
import { HydrogeologyComponent } from './components/hydrogeology/hydrogeology.component';

@Component({
  selector: 'app-overview',
  templateUrl: './overview.component.html',
  styleUrls: ['./overview.component.scss']
})
export class OverviewComponent implements OnInit, OnDestroy {
  map = null;
  isFirstLoad = true;  // 是否首次架加载

  menuList = null;
  statsList = null;
  // 侧边栏的状态是否是关闭的
  closeSelectItem = null;
  subscription = [];
  // 改变指标卡的颜色
  changeColor = false;
  layerIds = [];
  urlPath = "overview";
  menuId = "";

  constructor(
    private mapService: MapService,
    private overviewService: OverviewService,
    private menuService: MenuService,
    private layerMsgService: LayerMessageService,
    private layerManageService: LayerManageService,
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private modal: NzModalService
  ) {
    const urlArr = this.router.url.split("/")
    if (urlArr && urlArr.length > 0) {
      this.urlPath = urlArr[urlArr.length - 1];
      this.getSideMenuList(this.urlPath);
    }
  }

  ngOnInit() {
    this.mapService.init().then((map: any) => {
      if (!map) return;
      this.map = map;
      if (map.isStyleLoaded()) {
        // this.initPlotsLayer();
        this.mapInit(map);
      } else {
        map.on('load', () => {
          // this.initPlotsLayer();
          this.mapInit(map);
        });
      }
    });
    // 获取侧边栏选项
    this.subscription.push(
      postal.channel('CHANGE_COLOR').subscribe('set-color', res => {
        if (res) {
          this.changeColor = true;
        } else {
          this.changeColor = false;
        }
      }));
  }

  setColor() {
    const color = sessionStorage.getItem('card_color');
    if (color === 'true') {
      this.changeColor = true;
    } else {
      this.changeColor = false;
    }
  }
  private isValidFeature(features) {
    return features && Array.isArray(features) && features.length
  }
  // 场地详细信息
  private showCDClusterPropertiesInfo(features) {
    let isValid = this.isValidFeature(features)
    if (!isValid) return

    let properties = features[0].properties
    const modal = this.modal.create({
      nzTitle: properties?.名称,
      nzContent: MapFeatureInfoComponent,
      nzWidth: '40%',
      nzComponentParams: {
        properties: properties,
        keys: Object.keys(properties)
      },
      nzOnOk: () => { },
      nzFooter: null,
    });
  }

  // 气象站-天气详情
  private showWeatherPropertiesInfo(features) {

    let isValid = this.isValidFeature(features)
    if (!isValid) return

    let properties = features[0].properties
    const modal = this.modal.create({
      nzTitle: properties?.名称,
      nzContent: MapFeatureInfoComponent,
      nzWidth: '40%',
      nzComponentParams: {
        properties: properties,
        keys: ['名称', '国别', '级别', '维度', '经度', '气温', '天气', '降雨', '风向', '风级']
      },
      nzOnOk: () => { },
      nzFooter: null,
    });
  }

  // 降雨趋势图
  showRainfallTrend(features) {

    let isValid = this.isValidFeature(features)
    if (!isValid) return
    let properties = features[0].properties
    // 当前时间往前三天
    this.overviewService.getRainFallData({
      COUNTMODE: 2,
      STATIONID: properties.STATIONID,
      starttime: dayjs(new Date().getTime() - 3 * 24 * 3600 * 1000).format('YYYYMMDDHHmmss'),
      endtime: dayjs().format('YYYYMMDDHHmmss')
    }).subscribe(result => {
      const modal = this.modal.create({
        nzTitle: properties?.STATIONNAME,
        nzContent: RainfallTrendComponent,
        nzWidth: '60%',
        nzComponentParams: {
          data: result,
        },
        nzOnOk: () => { },
        nzFooter: null,
      });
    })
  }

  showWaterLevel(features) {

    let isValid = this.isValidFeature(features)
    if (!isValid) return
    let properties = features[0].properties
    let name = properties?.name
    this.overviewService.geWaterCodeByName({ name }).subscribe(data => {
      if (data && data.result && data.result.length) {
        let code = data.result[0].code
        this.overviewService.geWaterLeveDatalByCode({ stcd: code }).subscribe((levelData: any) => {
          if (levelData && levelData.result) {
            const modal = this.modal.create({
              nzTitle: name,
              nzContent: WaterLevelComponent,
              nzWidth: '60%',
              nzComponentParams: {
                data: levelData.result,
              },
              nzOnOk: () => { },
              nzFooter: null,
            });
          }
        })
      }
    })
  }

  // 水文地质
  showHydrogeology(features) {
    let isValid = this.isValidFeature(features)
    if (!isValid) return
    let properties = features[0].properties
    const modal = this.modal.create({
      nzTitle: properties?.title,
      nzContent: HydrogeologyComponent,
      nzWidth: '400px',
      nzComponentParams: {
        properties: properties,
        keys: ['id','title','layer','marker','x','y']
      },
      nzOnOk: () => { },
      nzFooter: null,
    });
  }

  mapInit(map) {
    if (!this.isFirstLoad) {
      return
    }
    map.on('mouseenter', 'clusters', function () {
      map.getCanvas().style.cursor = 'pointer';
    });
    map.on('mouseleave', 'clusters', function () {
      map.getCanvas().style.cursor = '';
    });
    map.on('mouseenter', 'atlasdata-ext-layer-8755d85b81', function () {
      map.getCanvas().style.cursor = 'pointer';
    });
    map.on('mouseleave', 'atlasdata-ext-layer-8755d85b81', function () {
      map.getCanvas().style.cursor = '';
    });
    map.on('click', 'clusters', function (e) {
      var features = map.queryRenderedFeatures(e.point, {
        layers: ['clusters']
      });
      var clusterId = features[0].properties.cluster_id;
      map.getSource('plots').getClusterExpansionZoom(
        clusterId,
        function (err, zoom) {
          if (err) return;
          map.easeTo({
            center: features[0].geometry.coordinates,
            zoom: zoom
          });
        }
      );
    });
    // 场地
    map.on('click', "atlasdata-ext-layer-8755d85b81", (e) => {
      this.showCDClusterPropertiesInfo(e?.features)
    })
    // 气象站
    map.on('click', "atlasdata-ext-layer-880d175a52", (e) => {
      this.showWeatherPropertiesInfo(e?.features)
    })
    // 降雨
    map.on('click', "atlasdata-ext-layer-91e3a7c867", (e) => {
      this.showRainfallTrend(e?.features)
    })
    // 水位监测
    map.on('click', "atlasdata-ext-layer-bc2147aa26", (e) => {
      this.showWaterLevel(e?.features)
    })

    //水文地质-地质勘探孔
    map.on('click', 'atlasdata-ext-layer-91d049e9e1', (e) => {
      this.showHydrogeology(e?.features)
    })

    map.on("click", (e) => {
      const feature = this.getFeatureOnClick(map, e);
      if (!feature) {
        return;
      } else if (feature.layer.id.indexOf("atlasdata-ext-layer-8755d85b81") >= 0) {
        this.focus(feature.properties);
      }
    });
    this.isFirstLoad = false;
  }

  // 获取侧边栏菜单
  getSideMenuList(id) {
    this.menuService.getSideMenuList(id).subscribe(res => {
      this.menuList = res;
      this.setColor(); // 总指标
      if (res.length > 0 || res[0].id) {
        this.getStats(res[0].id);
      }
    });
  }

  // 得到侧边栏项目
  getSideMenuItem(e) {
    const { id } = e.data;
    if (this.menuId === id) {
      return;
    }
    this.menuId = id;
    this.mapService.removeLayerByIds(this.layerIds);
    this.layerMsgService.clearSpecleLayer(this.menuList);
    //加载新的专题
    const controllTree = { rlayer: e.data.rlayer, active: e.visible };
    this.layerMsgService.publishControllLayer(controllTree);
    //加载聚合图层
    // if (id === this.menuList[0].id) {
    // this.layerIds = []
    // this.initPlotsLayer();
    // }
    //获取统计指标
    this.getStats(id);
  }

  //获取统计指标
  getStats(menuId = "changdifenbu") {
    this.overviewService.getStatsData(menuId).subscribe((data) => {
      this.statsList = data;
    });
  }

  initPlotsLayer = () => {
    if (!this.map) return;
    if (this.isFirstLoad) {
      if(this.map.getSource('plots'))   this.map.removeSource('plots')
      if(this.map.getLayer('clusters')) this.map.removeLayer('clusters')
      this.map.addSource('plots', {
        type: 'geojson',
        data: './mock-data/plots.geojson?t=' + new Date().getTime(),
        cluster: true,
        clusterMaxZoom: 15,
        clusterRadius: 128
      });
    }
    // 添加聚合图层plots-layer
    this.map.addLayer({
      'id': 'clusters',
      'type': 'circle',
      'source': 'plots',
      'paint': {
        'circle-radius': [
          'step',
          ['get', 'point_count'],
          30,
          15,
          40,
          50,
          50,
          100,
          60
        ],
        'circle-color': [
          'step',
          ['get', 'point_count'],
          '#51bbd6',
          15,
          '#f1f075',
          50,
          '#ffbf00',
          100,
          '#f28cb1'
        ],
        "circle-opacity": 0.8,
      },
      "filter": ["has", "point_count"],
      "minzoom": 5,
      "maxzoom": 8,
    });
    // 添加聚合数字图层cluster-count
    this.map.addLayer({
      "id": "cluster-count",
      "type": "symbol",
      "source": "plots",
      "layout": {
        "text-field": "{point_count}",
        "text-size": 16
      },
      "paint": {
        "text-color": "#000"
      },
      "filter": ["has", "point_count"],
      "minzoom": 5,
      "maxzoom": 8,
    });
    this.layerIds.push("clusters", "cluster-count");
    return;
    //添加场地点符号层unclustered-point
    this.map.addLayer({
      id: 'unclustered-point',
      type: 'circle',
      source: 'plots',
      filter: ['!', ['has', 'point_count']],
      paint: {
        'circle-color': '#11b4da',
        'circle-radius': 10,
        'circle-stroke-width': 1,
        'circle-stroke-color': '#fff',
        "circle-translate": [0, 26]
      },
    });
    //添加场地标注层unclustered-point-symbol
    this.map.addLayer({
      id: 'unclustered-point-symbol',
      type: 'symbol',
      source: 'plots',
      filter: ['!', ['has', 'point_count']],
      layout: {
        "text-field": "{名称}",
        "text-size": 12,
        "text-font": ["Microsoft YaHei Regular"],

      },
      paint: {
        "text-color": "#ffffff",
        "text-halo-width": 1,
        "text-halo-blur": 1,
        "text-halo-color": "rgba(0,0,0,.3)",
      },
    });
    this.layerIds.push("unclustered-point", "unclustered-point-symbol");
  }

  getFeatureOnClick(map, e) {
    if (!map) return;
    const bbox = {
      width: 10,
      height: 10
    };
    return map.queryRenderedFeatures([
      [e.point.x - bbox.width / 2, e.point.y - bbox.height / 2],
      [e.point.x + bbox.width / 2, e.point.y + bbox.height / 2]
    ])[0];
  }

  focus = (f) => {
    this.map.once("zoomend", () => {
    });
    this.map.flyTo({
      center: [120.24047, 31.76716],
      zoom: 17.2,
    });
  }

  ngOnDestroy(): void {
    this.mapService.removeLayerByIds(this.layerIds);
    this.subscription.forEach(element => {
      element.unsubscribe();
    });
    this.layerMsgService.clearSpecleLayer(this.menuList);
  }
}
